<?php

class DispatchdetailsController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';
    public $customer;
    public $location;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users'=>array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Dispatchdetails;


        if (isset($_POST)) {
            $model->attributes = $_POST;
            if ($model->save()) {
                echo json_encode(array(
                    'success' => true,
                    'msg' => "Saving successful"
                ));
            } else {
                echo json_encode(array(
                    'success' => false,
                    'errors' => $model->getErrors()
                ));
            }
        }
    }
    public function actionClose($dispatch){
       $model = $this->loadModel($dispatch);
        $user=Users::model()->findByPk(Yii::app()->user->id);
        $model->lastestTech->changeStatus($_POST['status'], $user->employeeid);
        $note = new Notes();
        if(isset($_POST['private']) && $_POST['private']=='on'){
            $note->private=1;
        }
        $note->note = $_POST['note'];
        $note->empno = $user->employeeid;
        $note->dispatch = $dispatch;
        $note->dateofnote = DateUtil::getDefaultCurrentDateTime();
        echo json_encode($note->save());
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($dispatch) {
        $model = $this->loadModel($dispatch);
        $this->loadObject($model->custno, $model->locno);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Dispatchdetails'])) {
            $model->attributes = $_POST['Dispatchdetails'];
            if ($model->save()){}
                
        }
        outputJsByList(Employees::model()->getEmployeeList(), 'employeeList');        
        outputJsByList(Statuscode::getList(), 'dispatchStatusCodeList');
        outputJsByList(Dispatchequipment::model()->getEquipmentList($dispatch), 'equipment',true);
        $dispatchLevel = DispatchUtil::getDispatchLevel($model->dispatch); 
        $this->render('update', array(
            'model' => $model,
            'location' => $this->location,
            'dispatchLevel'=>$dispatchLevel,
	    'contacts'=>$this->location->getLocationcontacts()
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($dispatch) {

        // we only allow deletion via POST request
        $model = $this->loadModel($dispatch);     
        $model->delete();
     
    }

    /**
     * Lists all models.
     */
    public function actionIndex($custno, $locno) {
        $this->loadObject($custno, $locno);

        outputJsByList(Dispatchdetails::model()->getDepartmentList(), 'department');
        outputJsByList(Dispatchdetails::model()->getPriorityList(), 'priority');        
        
        $curJobList=Jobs::model()->findAll('locno=:locno AND custno=:custno',array(
            'custno'=>$custno,
            'locno'=>$locno
        ));
        $jobList=array();
        foreach($curJobList as $item){
            $jobList[$item->jobid]=$item->jobid;
        }
        outputJsByList($jobList, 'job');
        
        $requirePO=Yii::app()->db->createCommand('select requirepo from tbl_customers where custno=:custno')->bindValue('custno', $custno)->queryScalar();
        if($requirePO===false){
            $requirePO=0;
        }
        Yii::app()->clientScript->registerScript('requirepo',"var requirePO=$requirePO;",  CClientScript::POS_HEAD);
        $this->render('index', array(
            'customer' => $this->customer,
            'location' => $this->location,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Dispatchdetails::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function loadObject($custno, $locno) {
        $this->location = Locations::model()->find('locno=:locno AND custno=:custno', array(
            'locno' => $locno,
            'custno'=>$custno
                ));
        $this->customer = Customers::model()->find('custno=:custno', array(
            'custno' => $custno
                ));
        if ($this->location === null || $this->customer === null)
            throw new CHttpException(404, 'The requested page does not exist.');
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'dispatchdetails-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionList($custno, $locno, $page=0, $sort=NULL) {
        if ($page > 0)
            $page--;
        $order = CJSON::decode($sort);

        $data = new CActiveDataProvider('Dispatchdetails', array(
                    'criteria' => array(
                        'condition' => 'custno=:custno AND locno=:locno',
                        'params' => array(
                            'custno' => $custno,
                            'locno' => $locno,
                        ),
                        'order' => isset($order) ? $order[0]['property'] . ' ' . $order[0]['direction'] : NULL
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page
                    )
                ));

        if ($data != NULL && count($data->getData()) > 0) {
            $rs = array();
            $rs['totalCount'] = $data->getTotalItemCount();
            foreach ($data->getData() as $i => $item) {

                $rs['data'][$i] = $item->getAttributes();
                if ($item->lastestTech != NULL) {
                    if($item->lastestTech->employee!=NULL){
                        $rs['data'][$i]['technician'] = $item->lastestTech->employee->firstname . ' ' . $item->lastestTech->employee->lastname;
                        $rs['data'][$i]['techStatus']=$item->lastestTech->status;
                    }
                    $rs['data'][$i]['techStatus'] = $item->lastestTech->status;
                }
                $rs['data'][$i]['department'] = $item->department;
            }
            echo json_encode($rs);
        }
        Yii::app()->end();
    }

    public function actionSave($dispatch,$next=0){
        $model = Dispatchdetails::model()->findByPk($dispatch);
        if($model!=null){
            if(isset($_POST['Dispatchdetails'])){

                $model->attributes = $_POST['Dispatchdetails'];
                if(isset($_POST['Dispatchdetails']['billparts']) && is_array($_POST['Dispatchdetails']['billparts'])){
                    $model->billparts = $_POST['Dispatchdetails']['billparts'][1];    
                }
                $level1List = Yii::app()
                                ->db
                                ->createCommand('
                                    select * from tbl_dispatchdetails 
                                    where (billingtype=0 or billingtype is null) 
                                        and complete is not null 
                                        and  (invoice is null or invoice="")')
                                
                                ->queryAll();
                $level2List = Yii::app()
                                ->db
                                ->createCommand('
                                    select * from tbl_dispatchdetails 
                                    where billingtype =1 and complete is not null 
                                        and (invoice is null or invoice="")')                                           
                                ->queryAll();
                if($model->save()){
                    if($next==1){
                        
                        $nextDispatch = null;                                        
                        for($i=0;$i<count($level1List);$i++){
                            if($level1List[$i]['dispatch'] == $dispatch){
                                if(isset($level1List[$i+1])){
                                    $nextDispatch = $level1List[$i+1];
                                    break;
                                }
                            }
                        }

                        if($nextDispatch == null){
                            
                            $nextDispatch = null;                                        
                            for($i=0;$i<count($level2List);$i++){
                                if($level2List[$i]['dispatch'] == $dispatch){
                                    if(isset($level2List[$i+1])){
                                        $nextDispatch = $level2List[$i+1];
                                        break;
                                    }
                                }
                            }
                        }
                        if($nextDispatch!=null){
                            $this->showAjaxMessage(
                                array(
                                    'next'=>$nextDispatch['dispatch'],
                                    'haveNext'=>true
                                ),true);    
                        }else{
                            $this->showAjaxMessage(
                                array(
                                    'haveNext'=>false
                                ),true
                            );
                        }
                        
                    }else{
                        $this->showAjaxMessage('',true);
                    }
                }else{
                    $this->showAjaxMessage(array('errors'=>$model->errors),false);
                }
            }
        }
    }

}

